home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python1.4_Source / Objects / floatobject.c < prev    next >
C/C++ Source or Header  |  1998-06-24  |  11KB  |  538 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Float object implementation */
  33.  
  34. /* XXX There should be overflow checks here, but it's hard to check
  35.    for any kind of float exception without losing portability. */
  36.  
  37. #include "allobjects.h"
  38. #include "modsupport.h"
  39.  
  40. #include <errno.h>
  41. #include <ctype.h>
  42. #include "mymath.h"
  43.  
  44. #include "protos/floatobject_protos.h"
  45.  
  46. #ifdef i860
  47. /* Cray APP has bogus definition of HUGE_VAL in <math.h> */
  48. #undef HUGE_VAL
  49. #endif
  50.  
  51. #if defined(HUGE_VAL) && !defined(CHECK)
  52. #define CHECK(x) if (errno != 0) ; \
  53.     else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \
  54.     else errno = ERANGE
  55. #endif
  56.  
  57. #ifndef CHECK
  58. #define CHECK(x) /* Don't know how to check */
  59. #endif
  60.  
  61. #ifdef HAVE_LIMITS_H
  62. #include <limits.h>
  63. #endif
  64.  
  65. #ifndef LONG_MAX
  66. #define LONG_MAX 0X7FFFFFFFL
  67. #endif
  68.  
  69. #ifndef LONG_MIN
  70. #define LONG_MIN (-LONG_MAX-1)
  71. #endif
  72.  
  73. #ifdef __NeXT__
  74. #ifdef __sparc__
  75. /*
  76.  * This works around a bug in the NS/Sparc 3.3 pre-release
  77.  * limits.h header file.
  78.  * 10-Feb-1995 bwarsaw@cnri.reston.va.us
  79.  */
  80. #undef LONG_MIN
  81. #define LONG_MIN (-LONG_MAX-1)
  82. #endif
  83. #endif
  84.  
  85. #if !defined(__STDC__) && !defined(macintosh)
  86. extern double fmod PROTO((double, double));
  87. extern double pow PROTO((double, double));
  88. #endif
  89.  
  90. object *
  91. #ifdef __SC__
  92. newfloatobject(double fval)
  93. #else
  94. newfloatobject(fval)
  95.     double fval;
  96. #endif
  97. {
  98.     /* For efficiency, this code is copied from newobject() */
  99.     register floatobject *op = (floatobject *) malloc(sizeof(floatobject));
  100.     if (op == NULL)
  101.         return err_nomem();
  102.     op->ob_type = &Floattype;
  103.     op->ob_fval = fval;
  104.     NEWREF(op);
  105.     return (object *) op;
  106. }
  107.  
  108. static void
  109. float_dealloc(op)
  110.     object *op;
  111. {
  112.     DEL(op);
  113. }
  114.  
  115. double
  116. getfloatvalue(op)
  117.     object *op;
  118. {
  119.     number_methods *nb;
  120.     floatobject *fo;
  121.     double val;
  122.     
  123.     if (op && is_floatobject(op))
  124.         return GETFLOATVALUE((floatobject*) op);
  125.     
  126.     if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
  127.         nb->nb_float == NULL) {
  128.         err_badarg();
  129.         return -1;
  130.     }
  131.     
  132.     fo = (floatobject*) (*nb->nb_float) (op);
  133.     if (fo == NULL)
  134.         return -1;
  135.     if (!is_floatobject(fo)) {
  136.         err_setstr(TypeError, "nb_float should return float object");
  137.         return -1;
  138.     }
  139.     
  140.     val = GETFLOATVALUE(fo);
  141.     DECREF(fo);
  142.     
  143.     return val;
  144. }
  145.  
  146. /* Methods */
  147.  
  148. void float_buf_repr Py_PROTO((char*,floatobject*));
  149.  
  150. void
  151. float_buf_repr(buf, v)
  152.     char *buf;
  153.     floatobject *v;
  154. {
  155.     register char *cp;
  156.     /* Subroutine for float_repr and float_print.
  157.        We want float numbers to be recognizable as such,
  158.        i.e., they should contain a decimal point or an exponent.
  159.        However, %g may print the number as an integer;
  160.        in such cases, we append ".0" to the string. */
  161.     sprintf(buf, "%.12g", v->ob_fval);
  162.     cp = buf;
  163.     if (*cp == '-')
  164.         cp++;
  165.     for (; *cp != '\0'; cp++) {
  166.         /* Any non-digit means it's not an integer;
  167.            this takes care of NAN and INF as well. */
  168.         if (!isdigit(Py_CHARMASK(*cp)))
  169.             break;
  170.     }
  171.     if (*cp == '\0') {
  172.         *cp++ = '.';
  173.         *cp++ = '0';
  174.         *cp++ = '\0';
  175.     }
  176. }
  177.  
  178. /* ARGSUSED */
  179. static int
  180. float_print(v, fp, flags)
  181.     floatobject *v;
  182.     FILE *fp;
  183.     int flags; /* Not used but required by interface */
  184. {
  185.     char buf[100];
  186.     float_buf_repr(buf, v);
  187.     fputs(buf, fp);
  188.     return 0;
  189. }
  190.  
  191. static object *
  192. float_repr(v)
  193.     floatobject *v;
  194. {
  195.     char buf[100];
  196.     float_buf_repr(buf, v);
  197.     return newstringobject(buf);
  198. }
  199.  
  200. static int
  201. float_compare(v, w)
  202.     floatobject *v, *w;
  203. {
  204.     double i = v->ob_fval;
  205.     double j = w->ob_fval;
  206.     return (i < j) ? -1 : (i > j) ? 1 : 0;
  207. }
  208.  
  209. static long
  210. float_hash(v)
  211.     floatobject *v;
  212. {
  213.     double intpart, fractpart;
  214.     int expo;
  215.     long x;
  216.     /* This is designed so that Python numbers with the same
  217.        value hash to the same value, otherwise comparisons
  218.        of mapping keys will turn out weird */
  219.  
  220. #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
  221. {
  222.     extended e;
  223.     fractpart = modf(v->ob_fval, &e);
  224.     intpart = e;
  225. }
  226. #else
  227.     fractpart = modf(v->ob_fval, &intpart);
  228. #endif
  229.  
  230.     if (fractpart == 0.0) {
  231.         if (intpart > 0x7fffffffL || -intpart > 0x7fffffffL) {
  232.             /* Convert to long int and use its hash... */
  233.             object *w = dnewlongobject(v->ob_fval);
  234.             if (w == NULL)
  235.                 return -1;
  236.             x = hashobject(w);
  237.             DECREF(w);
  238.             return x;
  239.         }
  240.         x = (long)intpart;
  241.     }
  242.     else {
  243.         fractpart = frexp(fractpart, &expo);
  244.         fractpart = fractpart*2147483648.0; /* 2**31 */
  245.         x = (long) (intpart + fractpart) ^ expo; /* Rather arbitrary */
  246.     }
  247.     if (x == -1)
  248.         x = -2;
  249.     return x;
  250. }
  251.  
  252. static object *
  253. float_add(v, w)
  254.     floatobject *v;
  255.     floatobject *w;
  256. {
  257.     return newfloatobject(v->ob_fval + w->ob_fval);
  258. }
  259.  
  260. static object *
  261. float_sub(v, w)
  262.     floatobject *v;
  263.     floatobject *w;
  264. {
  265.     return newfloatobject(v->ob_fval - w->ob_fval);
  266. }
  267.  
  268. static object *
  269. float_mul(v, w)
  270.     floatobject *v;
  271.     floatobject *w;
  272. {
  273.     return newfloatobject(v->ob_fval * w->ob_fval);
  274. }
  275.  
  276. static object *
  277. float_div(v, w)
  278.     floatobject *v;
  279.     floatobject *w;
  280. {
  281.     if (w->ob_fval == 0) {
  282.         err_setstr(ZeroDivisionError, "float division");
  283.         return NULL;
  284.     }
  285.     return newfloatobject(v->ob_fval / w->ob_fval);
  286. }
  287.  
  288. static object *
  289. float_rem(v, w)
  290.     floatobject *v;
  291.     floatobject *w;
  292. {
  293.     double vx, wx;
  294.     double /* div, */ mod;
  295.     wx = w->ob_fval;
  296.     if (wx == 0.0) {
  297.         err_setstr(ZeroDivisionError, "float modulo");
  298.         return NULL;
  299.     }
  300.     vx = v->ob_fval;
  301.     mod = fmod(vx, wx);
  302.     /* div = (vx - mod) / wx; */
  303.     if (wx*mod < 0) {
  304.         mod += wx;
  305.         /* div -= 1.0; */
  306.     }
  307.     return newfloatobject(mod);
  308. }
  309.  
  310. static object *
  311. float_divmod(v, w)
  312.     floatobject *v;
  313.     floatobject *w;
  314. {
  315.     double vx, wx;
  316.     double div, mod;
  317.     wx = w->ob_fval;
  318.     if (wx == 0.0) {
  319.         err_setstr(ZeroDivisionError, "float divmod()");
  320.         return NULL;
  321.     }
  322.     vx = v->ob_fval;
  323.     mod = fmod(vx, wx);
  324.     div = (vx - mod) / wx;
  325.     if (wx*mod < 0) {
  326.         mod += wx;
  327.         div -= 1.0;
  328.     }
  329.     return mkvalue("(dd)", div, mod);
  330. }
  331.  
  332. static double powu(x, n)
  333.     double x;
  334.     long n;
  335. {
  336.     double r = 1.;
  337.     double p = x;
  338.     long mask = 1;
  339.     while (mask > 0 && n >= mask) {
  340.         if (n & mask)
  341.             r *= p;
  342.         mask <<= 1;
  343.         p *= p;
  344.     }
  345.     return r;
  346. }
  347.  
  348. static object *
  349. float_pow(v, w, z)
  350.     floatobject *v;
  351.     object *w;
  352.     floatobject *z;
  353. {
  354.     double iv, iw, ix;
  355.     long intw;
  356.  /* XXX Doesn't handle overflows if z!=None yet; it may never do so :(
  357.   * The z parameter is really only going to be useful for integers and
  358.   * long integers.  Maybe something clever with logarithms could be done.
  359.   * [AMK]
  360.   */
  361.     iv = v->ob_fval;
  362.     iw = ((floatobject *)w)->ob_fval;
  363.     intw = (long)iw;
  364.     if (iw == intw && -10000 < intw && intw < 10000) {
  365.         /* Sort out special cases here instead of relying on pow() */
  366.         if (intw == 0) {         /* x**0 is 1, even 0**0 */
  367.              if ((object *)z!=None) {
  368.                  ix=fmod(1.0, z->ob_fval);
  369.                  if (ix!=0 && z->ob_fval<0) ix+=z->ob_fval;
  370.             }
  371.              else ix=1.0;
  372.                 return newfloatobject(ix); 
  373.         }
  374.         errno = 0;
  375.         if (intw > 0)
  376.             ix = powu(iv, intw);
  377.         else
  378.             ix = 1./powu(iv, -intw);
  379.     }
  380.     else {
  381.         /* Sort out special cases here instead of relying on pow() */
  382.         if (iv == 0.0) {
  383.             if (iw < 0.0) {
  384.                 err_setstr(ValueError,
  385.                        "0.0 to a negative power");
  386.                 return NULL;
  387.             }
  388.             return newfloatobject(0.0);
  389.         }
  390.         if (iv < 0.0) {
  391.             err_setstr(ValueError,
  392.                    "negative number to a float power");
  393.             return NULL;
  394.         }
  395.         errno = 0;
  396.         ix = pow(iv, iw);
  397.     }
  398.     CHECK(ix);
  399.     if (errno != 0) {
  400.         /* XXX could it be another type of error? */
  401.         err_errno(OverflowError);
  402.         return NULL;
  403.     }
  404.      if ((object *)z!=None) {
  405.          ix=fmod(ix, z->ob_fval);    /* XXX To Be Rewritten */
  406.          if ( ix!=0 &&
  407.               ((iv<0 && z->ob_fval>0) || (iv>0 && z->ob_fval<0) )) {
  408.              ix+=z->ob_fval;
  409.             }
  410.     }
  411.     return newfloatobject(ix);
  412. }
  413.  
  414. static object *
  415. float_neg(v)
  416.     floatobject *v;
  417. {
  418.     return newfloatobject(-v->ob_fval);
  419. }
  420.  
  421. static object *
  422. float_pos(v)
  423.     floatobject *v;
  424. {
  425.     INCREF(v);
  426.     return (object *)v;
  427. }
  428.  
  429. static object *
  430. float_abs(v)
  431.     floatobject *v;
  432. {
  433.     if (v->ob_fval < 0)
  434.         return float_neg(v);
  435.     else
  436.         return float_pos(v);
  437. }
  438.  
  439. static int
  440. float_nonzero(v)
  441.     floatobject *v;
  442. {
  443.     return v->ob_fval != 0.0;
  444. }
  445.  
  446. static int
  447. float_coerce(pv, pw)
  448.     object **pv;
  449.     object **pw;
  450. {
  451.     if (is_intobject(*pw)) {
  452.         long x = getintvalue(*pw);
  453.         *pw = newfloatobject((double)x);
  454.         INCREF(*pv);
  455.         return 0;
  456.     }
  457.     else if (is_longobject(*pw)) {
  458.         *pw = newfloatobject(dgetlongvalue(*pw));
  459.         INCREF(*pv);
  460.         return 0;
  461.     }
  462.     return 1; /* Can't do it */
  463. }
  464.  
  465. static object *
  466. float_int(v)
  467.     object *v;
  468. {
  469.     double x = getfloatvalue(v);
  470.     if (x < 0 ? (x = ceil(x)) < (double)LONG_MIN
  471.               : (x = floor(x)) > (double)LONG_MAX) {
  472.         err_setstr(OverflowError, "float too large to convert");
  473.         return NULL;
  474.     }
  475.     return newintobject((long)x);
  476. }
  477.  
  478. static object *
  479. float_long(v)
  480.     object *v;
  481. {
  482.     double x = getfloatvalue(v);
  483.     return dnewlongobject(x);
  484. }
  485.  
  486. static object *
  487. float_float(v)
  488.     object *v;
  489. {
  490.     INCREF(v);
  491.     return v;
  492. }
  493.  
  494.  
  495. static number_methods float_as_number = {
  496.     (binaryfunc)float_add, /*nb_add*/
  497.     (binaryfunc)float_sub, /*nb_subtract*/
  498.     (binaryfunc)float_mul, /*nb_multiply*/
  499.     (binaryfunc)float_div, /*nb_divide*/
  500.     (binaryfunc)float_rem, /*nb_remainder*/
  501.     (binaryfunc)float_divmod, /*nb_divmod*/
  502.     (ternaryfunc)float_pow, /*nb_power*/
  503.     (unaryfunc)float_neg, /*nb_negative*/
  504.     (unaryfunc)float_pos, /*nb_positive*/
  505.     (unaryfunc)float_abs, /*nb_absolute*/
  506.     (inquiry)float_nonzero, /*nb_nonzero*/
  507.     0,        /*nb_invert*/
  508.     0,        /*nb_lshift*/
  509.     0,        /*nb_rshift*/
  510.     0,        /*nb_and*/
  511.     0,        /*nb_xor*/
  512.     0,        /*nb_or*/
  513.     (coercion)float_coerce, /*nb_coerce*/
  514.     (unaryfunc)float_int, /*nb_int*/
  515.     (unaryfunc)float_long, /*nb_long*/
  516.     (unaryfunc)float_float, /*nb_float*/
  517.     0,        /*nb_oct*/
  518.     0,        /*nb_hex*/
  519. };
  520.  
  521. typeobject Floattype = {
  522.     OB_HEAD_INIT(&Typetype)
  523.     0,
  524.     "float",
  525.     sizeof(floatobject),
  526.     0,
  527.     (destructor)float_dealloc, /*tp_dealloc*/
  528.     (printfunc)float_print, /*tp_print*/
  529.     0,            /*tp_getattr*/
  530.     0,            /*tp_setattr*/
  531.     (cmpfunc)float_compare, /*tp_compare*/
  532.     (reprfunc)float_repr, /*tp_repr*/
  533.     &float_as_number,    /*tp_as_number*/
  534.     0,            /*tp_as_sequence*/
  535.     0,            /*tp_as_mapping*/
  536.     (hashfunc)float_hash, /*tp_hash*/
  537. };
  538.